#Copyright Ken Faulkner 2007.
import os
from Common.logRoutine import *
import traceback
import datetime
import threading
import os.path
import os
import subprocess

class MpegEncoder(threading.Thread):
  
  # lower number, lower quality
  LEVEL_PHONE = 0
  LEVEL_MID   = 1
  LEVEL_VOICE = 2
  LEVEL_CD    = 3
  
  # should probably whack into a config file.
  levelDict = { LEVEL_MID:"mw-us", LEVEL_PHONE:"phone", LEVEL_VOICE:"fm", LEVEL_VOICE:"cd" }
  
  def __init__(self, config, user_config):
    self.config = config
    self.log = getLogger()
    self.user_config = user_config
  
  def generateMpeg(self, filename, item ):
    """
    Covert the file (assumed to be a wav file) to an mp3.
    Apply tags
    
    Returns filename of mp3.
    """
    self.log.info("MpegEncoder::generateMpeg start")
    
    mp3Filename = ""
    
    try:
    
      wavFilename = self.__generateWav( filename )
      
      # erm.. dumb!
      title = item.title
      album = item.album
      artist = item.title

      epNo = item.episode_no
      
      mp3Filename = os.path.join( self.user_config['DownloadDir'], title + '-' + str( epNo ) + '-' + str( item.date ) + ".mp3" )
      mp3Filename = mp3Filename.replace(" ", "_")
      
      # yeah, going to replace the ' with nothing on the next line.
      mp3Filename = mp3Filename.replace("&#39;", "'")
      
      mp3Filename = mp3Filename.replace("'", "")
      
      encodeLevel = self.user_config.get( 'EncodingLevel', MpegEncoder.LEVEL_VOICE)
      
      self.log.debug("encode Level " + str( encodeLevel ) )
      
      encodeLevelString = self.levelDict.get( encodeLevel, "fm"  )

      # if binary starts with a / then its an absolute path
      # else its relative.
      lameBinary = self.user_config['LameBinary']
      
      lameCommand = '%s --preset %s %s %s --tt "%s" --ta "%s" --tl "%s" --tn "%s" '%( lameBinary, encodeLevelString, wavFilename, mp3Filename, title, artist, album, epNo )
      
      self.log.debug("lame command is " + lameCommand )
     
      #p = subprocess.Popen( lameCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
      #pid, sts = os.waitpid(p.pid, 0)
      os.system( lameCommand )
      os.remove( wavFilename )
 
      # adjust item to remember its own mp3 filename. 
      item.mp3_filename = mp3Filename
      
    except:
      self.log.error("MpegEncoder::generateMpeg ex " + traceback.format_exc() )
 
  def __generateWav(self, filename ):
    """
    Covert the file to a wav
    
    Returns filename of wav
    """
    self.log.info("MpegEncoder::generateWav start")
    
    wavFilename = ""
    
    try:
    
      self.log.debug("file is " + filename )
      
      wavFilename =  filename + ".wav"
      wavFilename = wavFilename.replace(" ", "_")
      
      bn = os.path.basename( wavFilename )
      dn = os.path.dirname( wavFilename )
      
      os.chdir( dn )
      
      self.log.debug("changing dir to " + dn )
      
      mplayerBinary = self.user_config['MPlayerBinary']
      
      mplayerBinary = mplayerBinary.replace(" ", "\ ")
      
      command = mplayerBinary + ' -ao pcm:file=%s %s '%( bn, filename )
      
      self.log.debug("wav encoding command is " + command )
      
      os.system( command )
      os.remove( filename )
      
      
    except:
      self.log.error("MpegEncoder::generateWav ex " + traceback.format_exc() )
 
    return wavFilename
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
